package org.jeecg.modules.basic.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entrance.entity.LwgyEntranceGuard;
import org.jeecg.modules.basic.entrance.service.ILwgyEntranceGuardService;
import org.jeecg.modules.basic.entry.entity.LwgyAbnormalAction;
import org.jeecg.modules.basic.entry.entity.LwgyInoutRecord;
import org.jeecg.modules.basic.entry.service.ILwgyAbnormalActionService;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *待修改，定时器生存异常数据的时候，顺便生成相应的excel数据
 * @author sn
 * @date 2022-09-23 15:20
 * 晚上10点（配置表中最晚时间）-定时器执行时间未回的学生叫做晚归：
 * 离线上传数据也会正常在里面，所以要去掉离线上传功能
 */
@Slf4j
public class AbnormalInfoJob implements Job {

    @Autowired
    private ILwgyEntranceGuardService lwgyEntranceGuardServic;
    @Autowired
    private ILwgyInoutRecordService lwgyInoutRecordService;
    @Autowired
    private ILwgyAbnormalActionService lwgyAbnormalActionService;
    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;
    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" 时间:" + DateUtils.getTimestamp()));
        List<LwgyEntranceGuard> list = lwgyEntranceGuardServic.list();
        //晚归的pushtype好像是1
        List<LwgyEntranceGuard> checkList = list.stream().filter(item ->
                item.getPushType().equals("1")).collect(Collectors.toList());
        if(oConvertUtils.isNotEmpty(checkList) && checkList.size()>0){
            //存在晚归的设置，可以进行推送
            LwgyEntranceGuard map = (LwgyEntranceGuard) checkList.get(0);
            String entranceTime = map.getEntranceTime();//超过这个时间的就算晚归
            if(oConvertUtils.isEmpty(entranceTime)){
                entranceTime="22:00";//没设置时间按照晚上十点算
            }
            String dateFormat =DateUtils.now();
            System.out.println("今天时间"+dateFormat);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间格式
            Date date = new Date(); //当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(date);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
            String beforeOneDay = sdf.format(calendar.getTime()); //得到前一天的时间
            String endTime = beforeOneDay.substring(0, 10) + " "+entranceTime+":00";
            System.out.println("endTime:"+endTime);
            QueryWrapper<LwgyInoutRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("direction", "1");
            queryWrapper.between("record_date",endTime,dateFormat);//进入时间小于当前时间，//晚于今天前一天的最晚时间，算晚归
            List<LwgyInoutRecord> wglist = lwgyInoutRecordService.list(queryWrapper);//---=====  关联查询xy,bed 等信息，一起保存
            //循环wglist ,写入异常表
            if(wglist.size()>0){
                //通过晚归信息，获取里面学生id.从而获取相应的学院和bed
                String[] numbers = wglist.stream().map(p -> p.getUserId()).collect(Collectors.toList()).toArray(new String[0]);
                //通过学号获取所有的学生信息，包括学生ｉｄ，学院专业等

                //通过学生id获取原床位信息
                List<LwgyBaseStudent> stuList = lwgyBaseStudentService.getStuListByStuNumber(numbers);
                String[] ids = stuList.stream().map(p -> p.getId()).collect(Collectors.toList()).toArray(new String[0]);
                List<LwgyBaseBed> bedList = lwgyBaseBedService.getBedListByStuId(ids);
                //获取学院信息床位信息end
                List<LwgyAbnormalAction> endList = new ArrayList<LwgyAbnormalAction>();
                wglist.stream().forEach(item->{

                    LwgyAbnormalAction lwgyAbnormalAction = new LwgyAbnormalAction();
                    List<LwgyBaseStudent> studentList = stuList.stream().filter(p -> p.getStudentNumber().equals(item.getUserId())).collect(Collectors.toList());
                    if(oConvertUtils.isNotEmpty(studentList) && studentList.size()>0 ){
                        LwgyBaseStudent lwgyBaseStudent = studentList.get(0);
                        lwgyAbnormalAction.setStudentid(lwgyBaseStudent.getId());
                        lwgyAbnormalAction.setStudentXy(lwgyBaseStudent.getStudentCollege());
                        lwgyAbnormalAction.setStudentZy(lwgyBaseStudent.getStudentMajor());
                        lwgyAbnormalAction.setStudentBj(lwgyBaseStudent.getStudentClass());
                        lwgyAbnormalAction.setStudentSex(lwgyBaseStudent.getStudentSex());
                        List<LwgyBaseBed> bedsList = bedList.stream().filter(d -> d.getStudentId().equals(lwgyBaseStudent.getId())).collect(Collectors.toList());
                        if(oConvertUtils.isNotEmpty(bedsList)  && bedsList.size()>0){
                            LwgyBaseBed lwgyBaseBed = bedsList.get(0);
                            lwgyAbnormalAction.setCampus(lwgyBaseBed.getCampusId());
                            lwgyAbnormalAction.setBuildingNum(lwgyBaseBed.getBuildingId());
                            lwgyAbnormalAction.setUnit(lwgyBaseBed.getUnitId());
                            lwgyAbnormalAction.setRoomNum(lwgyBaseBed.getRoomId());
                            lwgyAbnormalAction.setBedNum(lwgyBaseBed.getId());
                        }

                    }
                    lwgyAbnormalAction.setStuStatus("1");//晚归
                    lwgyAbnormalAction.setStudentName(item.getUserName());
                    lwgyAbnormalAction.setStudentNumber(item.getUserId());
                    lwgyAbnormalAction.setLastIntoStatus(item.getDirection());
                    lwgyAbnormalAction.setLastIntoTime(item.getRecordDate());
                    endList.add(lwgyAbnormalAction);
                    });
                lwgyAbnormalActionService.saveBatch(endList);

            }
        }
    }
}
